package com.baichang.taoshunda.service.impl;

import com.alipay.api.AppPay;
import com.baichang.framework.excelption.ServiceException;
import com.baichang.framework.model.Page;
import com.baichang.framework.utils.DateUtil;
import com.baichang.framework.utils.KidUtils;
import com.baichang.framework.utils.Spatial4jUtil;
import com.baichang.taoshunda.dao.*;
import com.baichang.taoshunda.entity.Bussiness;
import com.baichang.taoshunda.entity.CompanyPanymentHistory;
import com.baichang.taoshunda.entity.Goods;
import com.baichang.taoshunda.entity.em.payHistory;
import com.baichang.taoshunda.service.*;
import com.baichang.taoshunda.utils.ConvertTypeUtils;
import com.weixin.pay.api.WeixinPay;
import com.weixin.pay.api.model.PayInfo;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

//import com.baichang.taoshunda.service.DiscountActivityService;

/**
 * Created by Administrator on 2017/11/1 0001.
 */
@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private GoodsDao goodsDao;

    @Autowired
    private GoodsTypeDao goodsTypeDao;

    @Autowired
    private GoodsReportDao goodsReportDao;

    @Autowired
    private GoodsSpecService goodsSpecService;
    @Autowired
    private BussinessDao bussinessDao;
    @Autowired
    private CompanyPanymentHistoryDao companyPanymentHistoryDao;
    @Autowired
    private BusinessService businessService;
    @Autowired
    private FootmarkService footmarkService;
    //    @Autowired
//    private DiscountActivityService discountActivityService;
    @Autowired
    private ParamsService paramsService;
    @Autowired
    private GoodsTypeService goodsTypeService;
    @Autowired
    private FavoritesDao favoritesDao;
    @Autowired
    private ShopCarDao shopCarDao;
    @Autowired
    private OrderDetailsDao orderDetailsDao;
    @Autowired
    private OrderService orderService;
    @Autowired
    private CouponDao couponDao;
    @Autowired
    private PromotionDao promotionDao;


    /**
     * 活动下查询商品
     *
     * @param goodsBusId
     * @param type
     * @param goodsName
     * @param nowPage
     * @param pageSize   @return
     */
    @Override
    public Page queryOutGoods(String goodsBusId, Integer type, String goodsName, int nowPage, int pageSize) {
        return goodsDao.queryOutGoods(goodsBusId, type, goodsName, nowPage, pageSize);
    }

    /**
     * 广告位下的商品
     *
     * @param id
     * @param nowPage
     * @param pageSize
     * @return
     */
    @Override
    public Page queryOutCarouselGoods(Integer id, Integer type, int nowPage, int pageSize) {
        return goodsDao.queryOutCarouselGoods(id, type, nowPage, pageSize);
    }

    /**
     * 查询商品
     *
     * @param nowPage
     * @param pageSize
     * @param goodsName
     * @param busName
     * @param type      @return
     * @param business
     */
    @Override
    public Page queryGoods(int nowPage, int pageSize, String goodsName, String busName, Integer type, Integer business) {
        return goodsDao.queryGoods(nowPage, pageSize, goodsName, busName, type, business);
    }

    /**
     * 商品下架
     *
     * @param id
     * @param isUpper
     * @return
     */
    @Override
    public int updateIsUpper(Integer id, Integer isUpper) {
        return goodsDao.updateIsUpper(id, isUpper);
    }

    /**
     * 商品交易记录
     *
     * @param id
     * @param nowPage
     * @param pageSize
     * @return
     */
    @Override
    public Page queryGoodsOrder(Integer id, int nowPage, int pageSize) {
        return goodsDao.queryGoodsOrder(id, nowPage, pageSize);
    }

    /**
     * 下架和新添加的商品
     *
     * @param nowPage
     * @param pageSize
     * @param goodsName
     * @param busName
     * @param businessId
     * @param type       @return
     */
    @Override
    public Page queryNewOrOldGoods(int nowPage, int pageSize, String goodsName, String busName, Integer businessId, Integer type) {
        return goodsDao.queryNewOrOldGoods(nowPage, pageSize, goodsName, busName, businessId, type);
    }

    /**
     * 查询商品类型
     *
     * @param type
     * @return
     */
    @Override
    public List<Map<String, Object>> queryGoodsType(Integer type) {
        return goodsTypeDao.queryGoodsType(type);
    }

    @Override
    public Integer getCompanyGoodsNumber(Integer companyId) {
        return goodsDao.getCompanyGoodsNumber(companyId);
    }

    /**
     * 查询举报的商品
     *
     * @param nowPage
     * @param pageSize
     * @param name
     * @param busName  @return
     */
    @Override
    public Page queryReportGoods(int nowPage, int pageSize, String name, String busName) {
        return goodsReportDao.queryReportGoods(nowPage, pageSize, name, busName);
    }

    /**
     * 根据商品类别编号与用户购物车查询商品列表
     *
     * @param typeId
     * @param userId
     * @return
     */
    @Override
    public List<Map<String, Object>> findGoodsListByTypeIdAndShopCar(Integer typeId, Integer userId) {
        List<Map<String, Object>> returnMaps = new ArrayList<Map<String, Object>>();
        List<Map<String, Object>> maps = goodsDao.findGoodsListByTypeIdAndShopCar(typeId, userId);
        if (maps != null && maps.size() > 0) {
            for (Map<String, Object> map : maps) {
                Integer goodsId = ConvertTypeUtils.obj2Integer(map.get("id"));
                List<Map<String, Object>> specValues = goodsSpecService.findGoodsSpecByGoodsId(goodsId);
                Map<String, Object> newMap = map;
                newMap.put("specValues", specValues);
                returnMaps.add(newMap);
            }
        }
        return returnMaps;
    }

    /**
     * 根据商品类别编号与用户编号查看商品列表以及购物车内的数量
     *
     * @param typeId
     * @param userId
     * @return
     */
    @Override
    public List<Map<String, Object>> findGoodsListTakeoutByTypeIdAndShopCar(Integer typeId, Integer userId) {
        List<Map<String, Object>> returnMaps = new ArrayList<Map<String, Object>>();
        List<Map<String, Object>> maps = goodsDao.findGoodsListByTypeIdAndShopCar(typeId, userId);
        if (maps != null && maps.size() > 0) {
            for (Map<String, Object> map : maps) {
                Integer goodsId = ConvertTypeUtils.obj2Integer(map.get("id"));
                List<Map<String, Object>> specValues = goodsSpecService.findTakeoutGoodsSpecByGoodsId(goodsId);
//                List<Map<String, Object>> discountActivitys = discountActivityService.findDiscountListByGoodsId(goodsId);
                Map<String, Object> newMap = map;
                newMap.put("specValues", specValues);
//                newMap.put("discountActivitys", discountActivitys);
                returnMaps.add(newMap);
            }
        }
        return returnMaps;
    }

    /**
     * 查看商家商品分类下是否存在商品
     *
     * @param id
     * @return
     */
    @Override
    public int getGoodsCountByGoodsTypeId(Integer id) {

        return goodsDao.getGoodsCountByGoodsTypeId(id);
    }

    /**
     * 商家商品分类下的 商品
     *
     * @param bussId
     * @param goodsTypeId
     * @return
     */
    @Override
    public List<Map<String, Object>> findGoodsList(Integer bussId, Integer goodsTypeId) {
        List<Map<String, Object>> goodsList = goodsDao.findGoodsList(bussId, goodsTypeId);

        return goodsList;
    }

    /**
     * 添加商品
     *
     * @param cityId               城市编号
     * @param bussId               商家编号
     * @param name                 商品名称
     * @param price                现价
     * @param bagging              包装费
     * @param headPic              列表展示图片
     * @param images               商品图片
     * @param typeId               分类编号
     * @param unit                 单位
     * @param spec                 规格
     * @param isFree               是否免费
     * @param isInvoice            是否发票
     * @param bannerImages         背景图
     * @param goodsDetails         商品详情
     * @param isBespeak            是否可以预约
     * @param isNoReasonReturn     是否无理由退货
     * @param isHomeInstallation   是否上门安装
     * @param commercialActivities 商品活动
     * @param goodsVideo
     * @param goodsVideoImg        @return
     */
    @Override
    public Map<String, Object> addGoods(Integer cityId, Integer bussId, String name, Double oldPrice, Double price, Double bagging, String headPic, String images, Integer typeId, String unit, String spec, Integer isFree, Integer isInvoice, String bannerImages, String goodsDetails, Integer isBespeak, Integer isNoReasonReturn, Integer isHomeInstallation, String commercialActivities, String goodsVideo, String goodsVideoImg) throws ServiceException {
        Map<String, Object> map = new HashedMap();
//        int isRecord = companyPanymentHistoryDao.getCountRecord(bussId);
//        int goodsCount = goodsDao.getGoodsCountBYBusId(bussId);
        //根据参数类型，参数编号获取对应的值
//        int paramsType = 37;//参数类型
//        int paramsId = 36;//参数编号
//        Map<String, Object> score = paramsService.getParamsValue(paramsType, paramsId);
        //获取积分
//        int number = Integer.parseInt(score.get("value").toString());
//        if (isRecord == 0 && goodsCount >= number) {
//            throw new ServiceException("请先缴纳保障金再继续添加商品");
//        }
        boolean flag = false;
        Goods goods = new Goods();
        goods.setCompanyId(bussId);
        goods.setName(name);
        goods.setPrice(BigDecimal.valueOf(price));
        goods.setBoxPrice(BigDecimal.valueOf(bagging));
        goods.setHeadPic(headPic);
        goods.setGoodsTypeId(typeId);
        goods.setIsJoin(0);
        goods.setIsBespeak(isBespeak);
        goods.setIsNoReasonReturn(isNoReasonReturn);
        goods.setIsHomeInstallation(isHomeInstallation);
        goods.setIsUpper(1);
        goods.setIsFree(isFree);
        goods.setCommercialActivities(commercialActivities);
        goods.setIsInvoice(isInvoice);
        goods.setGoodsDetail(goodsDetails);
        goods.setBannerImages(bannerImages);
        goods.setOrderNum(0);
        goods.setIsSpecial(0);
        goods.setAllSaleNum(0);
        goods.setImages(images);
        if (!goodsVideo.equals("")) {
            goods.setStatus(0);
        } else {
            goods.setStatus(1);
        }
        goods.setStock(1000);
        goods.setUnit(unit);
        goods.setCityId(cityId);
        goods.setMonthSales(0);
        goods.setCreated(new Date());
        goods.setGoodsVideo(goodsVideo);
        goods.setGoodsVideoImg(goodsVideoImg);
        long id = goodsDao.save(goods);
        if (id > 0) {
            flag = true;
        }
        JSONArray jsonArray = JSONArray.fromObject(spec);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = JSONObject.fromObject(jsonArray.get(i));
            Integer isPrice = Integer.parseInt(jsonObject.get("isPrice").toString());
            Integer isImage = Integer.parseInt(jsonObject.get("isImage").toString());
            String specValue = jsonObject.get("spec").toString();
            flag = goodsSpecService.addSpec(isPrice, specValue, bussId, (int) id, isImage);
        }
        Map getValue = paramsService.getParamsValue(38, 37);
        BigDecimal totalMoney = BigDecimal.valueOf(Double.parseDouble(getValue.get("value").toString()));
        map.put("goodsId", id);
        map.put("goodsMoney", totalMoney);
        return map;
    }

    /**
     * 修改商品
     *
     * @param id
     * @param name
     * @param price
     * @param bagging
     * @param headPic
     * @param images
     * @param unit
     * @param spec
     * @param companyId
     * @param isBespeak
     * @param isHomeInstallation
     * @param isNoReasonReturn
     * @param goodsDetails
     * @param commercialActivities
     * @param isFree
     * @param isInvoice
     * @param bannerImages         @return
     * @param goodsVideo
     * @param goodsVideoImg
     */
    @Override
    public Map<String, Object> updateGoods(Integer id, String name, Double price, Double bagging, String headPic, String images, String unit, String spec, Integer companyId, Integer isBespeak, Integer isHomeInstallation, Integer isNoReasonReturn, String goodsDetails, String commercialActivities, Integer isFree, Integer isInvoice, String bannerImages, String goodsVideo, String goodsVideoImg) {
        boolean flag = false;
        Map<String, Object> map = new HashedMap();
        flag = goodsDao.updateGoods(id, name, price, bagging, headPic, images, unit, isBespeak, isHomeInstallation, isNoReasonReturn, goodsDetails, commercialActivities, isFree, isInvoice, bannerImages, goodsVideo, goodsVideoImg);
        JSONArray jsonArray = JSONArray.fromObject(spec);
        goodsSpecService.deleteByGoodsId(id);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = JSONObject.fromObject(jsonArray.get(i));
            Integer isImage = Integer.parseInt(jsonObject.get("isImage").toString());
            Integer isPrice = Integer.parseInt(jsonObject.get("isPrice").toString());
            String specValue = jsonObject.get("spec").toString();
            flag = goodsSpecService.updateSpecValue(isPrice, companyId, specValue, id, isImage);
        }
        Map getValue = paramsService.getParamsValue(38, 37);
        BigDecimal totalMoney = BigDecimal.valueOf(Double.parseDouble(getValue.get("value").toString()));
        map.put("goodsId", id);
        map.put("goodsMoney", totalMoney);
        return map;
    }

    /**
     * 删除商品
     *
     * @param id
     * @return
     */
    @Override
    public boolean deleteGoods(String id) {
        return goodsDao.updateGoodsStatus(id, 0) > 0;
    }

    /**
     * 修改上下架状态
     *
     * @param id
     * @param isUpper
     * @return
     */
    @Override
    public boolean updateGoodsIsUpper(Integer id, int isUpper) {
        return goodsDao.updateGoodsIsUpper(id, isUpper);
    }

    /**
     * 修改商品排序
     *
     * @param jsonData
     * @return
     */
    @Override
    public boolean updateGoodsOrderNum(String jsonData) {
        JSONArray jsonArray = JSONArray.fromObject(jsonData);
        boolean flag = false;
        if (jsonArray != null && jsonArray.size() > 0) {
            for (int i = 0; i < jsonArray.size(); i++) {
                Map<String, Object> map = (Map<String, Object>) jsonArray.get(i);
                Integer goodsId = ConvertTypeUtils.obj2Integer(map.get("goodsId"));
                Integer orderNumber = ConvertTypeUtils.obj2Integer(map.get("orderNumber"));
                flag = goodsDao.updateGoodsOrderNumber(goodsId, orderNumber) > 0;
            }
        }
        return flag;
    }

    /**
     * 查看商品详情
     *
     * @param goodsId
     * @param ulng
     * @param ulat    @return
     * @param userId
     */
    @Override
    public Map<String, Object> getGoodsDetails(Integer goodsId, double ulng, double ulat, int userId) throws ServiceException {
        Map<String, Object> map = new HashMap<String, Object>();
        Goods goods = goodsDao.getGoodsById(goodsId);
        if (goods != null) {
            Bussiness bussiness = bussinessDao.getEntityById(goods.getCompanyId());
            map.put("id", goods.getId());
            map.put("bussId", goods.getCompanyId());
            map.put("cityId", goods.getCityId());
            map.put("name", goods.getName());
            map.put("price", goods.getPrice());
            map.put("bagging", goods.getBoxPrice());
            map.put("bannerImages", goods.getBannerImages());
            map.put("goodsDetail", goods.getGoodsDetail());
            map.put("isBespeak", goods.getIsBespeak());
            map.put("isUpper", goods.getIsUpper());
            map.put("status", goods.getStatus());
            map.put("companyStatus", bussiness.getState());
            map.put("isHomeInstallation", goods.getIsHomeInstallation());
            map.put("isFree", goods.getIsFree());
            map.put("isNoReasonReturn", goods.getIsNoReasonReturn());
            map.put("commercialActivities", goods.getCommercialActivities());
            map.put("saleNum", goods.getMonthSales());
            map.put("bussName", bussiness.getBussName());
            map.put("headPic", goods.getHeadPic());
            map.put("discountMoney", goods.getDiscountMoney());
            map.put("discountNumber", goods.getDiscountNumber());
            map.put("stock", goods.getStock());
            map.put("expirationTime", goods.getExpirationTime());
            map.put("typeId", goods.getGoodsTypeId());
            map.put("goodsVideo", goods.getGoodsVideo());
            map.put("goodsVideoImg", goods.getGoodsVideoImg());
            map.put("isOpen", bussiness.getIsOpen());
            map.put("startTime", bussiness.getStartTime());
            map.put("endTime", bussiness.getEndTime());
            map.put("images", goods.getImages());
            map.put("isInvoice", bussiness.getIsInvoice());
            map.put("shopCarNum", shopCarDao.getCountByUserIdAndGoodsId(goodsId, userId));
            List<Map<String, Object>> maps = goodsSpecService.findGoodsSpecByGoodsId(goodsId);
            map.put("spec", maps);
            map.put("isDispatching", bussiness.getIsDispatching());
            map.put("unit", goods.getUnit());
            map.put("RyToken", JSONObject.fromObject(bussiness.getRyToken()).get("token"));
            map.put("RyId", JSONObject.fromObject(bussiness.getRyToken()).get("userId"));
            //计算距离
            double distace = Spatial4jUtil.getDistance(ulng, ulat, Double.parseDouble(bussiness.getLng()), Double.parseDouble(bussiness.getLat()));
            double dispathing = businessService.getDispatching(bussiness.getId(), BigDecimal.valueOf(distace), bussiness.getIsDispatching());
            map.put("dispathing", dispathing);
            //是否收藏
            int isFavorites = favoritesDao.getCountByUserAndBusId(goodsId, userId, 3);
            map.put("isFavorites", isFavorites);
            if (userId != 0) {
                int count = footmarkService.getCountByUser(userId, goodsId);
                if (count == 0) {
                    footmarkService.addFootMark(userId, goodsId, bussiness.getId());
                } else {
                    footmarkService.updateTime(userId, goodsId);
                }

            }
            Map getValue = paramsService.getParamsValue(38, 37);
            BigDecimal totalMoney = BigDecimal.valueOf(Double.parseDouble(getValue.get("value").toString()));
            map.put("goodsMoney", totalMoney);

        } else {
            map.put("status", 0);
        }
        return map;
    }

    /**
     * 查询商品详细
     *
     * @param goodsId
     * @param nowPage
     * @param pageSize
     * @return
     */
    @Override
    public Page queryGoodsDetails(Integer goodsId, int nowPage, int pageSize) {
        return goodsDao.queryGoodsDetails(goodsId, nowPage, pageSize);
    }

    /**
     * 广告位商品
     *
     * @param goodsId
     * @param nowPage
     * @param pageSize
     * @return
     */
    @Override
    public Page queryCarouselGoods(String goodsId, int nowPage, int pageSize) {
        return goodsDao.queryCarouselGoods(goodsId, nowPage, pageSize);
    }

    @Override
    public Map<String, Object> getSpecialGoods(int cityId, int nowPage, int pageSize, String uLng, String uLat) {

        List<Map<String, Object>> mapList = new ArrayList<>();
        //根据参数类型，参数编号获取对应的值
        int paramsType = 36;//参数类型
        int paramsId = 35;//参数编号
        Map<String, Object> score = paramsService.getParamsValue(paramsType, paramsId);
        //获取特价商品距离
        int distance = Integer.parseInt(score.get("value").toString());
        mapList = goodsDao.getSpecialGoods(cityId, nowPage, pageSize, uLng, uLat, distance);
        if (mapList.size() == 0) {
            nowPage = 1;
            mapList = goodsDao.getSpecialGoods(cityId, nowPage, pageSize, uLng, uLat, distance);
        }
        Map map = new HashMap<>();
        map.put("nowPage", nowPage);
        map.put("specialGoods", mapList);
        return map;
    }

    /**
     * 通过关键字查询商品
     *
     * @param nowPage
     * @param pageSize
     * @param cityId
     * @param key
     * @return
     */
    @Override
    public List<Map<String, Object>> getGoodsByKey(int nowPage, int pageSize, int cityId, String key) {
        return goodsDao.getGoodsByKey(nowPage, pageSize, cityId, key);
    }

    /**
     * 获取分类下的商品列表
     *
     * @param nowPage
     * @param pageSize
     * @param companyId
     * @param userId
     * @return
     */
    @Override
    public List<Map<String, Object>> getGoodsByBussAndTypeID(int nowPage, int pageSize, int companyId, int userId) throws ServiceException {
        List<Map<String, Object>> returnMaps = new ArrayList<Map<String, Object>>();
        List<Map<String, Object>> goodsMaps = new ArrayList<Map<String, Object>>();
//        Bussiness bussiness = businessService.getBusinessById(companyId);
//        if (bussiness != null) {
        List<Map<String, Object>> typeList = goodsTypeService.findCompanyGoodsType(companyId);
        if (typeList != null && typeList.size() > 0) {
            for (Map<String, Object> map : typeList) {
                Integer typeId = ConvertTypeUtils.obj2Integer(map.get("id"));
                //查询商品列表
                List<Map<String, Object>> goodsList = goodsDao.findGoodsListByTypeIdAndShopCar(typeId, userId);
                if (goodsList != null && goodsList.size() > 0) {
                    for (Map<String, Object> good : goodsList) {
                        Integer goodsId = ConvertTypeUtils.obj2Integer(good.get("id"));
//                        String images = good.get("headPic").toString();
//                        String splitString = StringUtils.substringBeforeLast(images, ".");
//                        String suffix = StringUtils.substringAfter(images, ".");
//                        good.put("headPic", splitString + "_300x300." + suffix);
                        List<Map<String, Object>> specValues = goodsSpecService.findTakeoutGoodsSpecByGoodsId(goodsId);
                        Map<String, Object> newMap = good;
                        newMap.put("specValues", specValues);
                        goodsMaps.add(newMap);
                    }
                }
                Map<String, Object> newMap = map;
                newMap.put("goodsList", goodsList);
                returnMaps.add(newMap);
            }
        }
//        }
        return returnMaps;
    }

    /**
     * 查询商家的全部商品
     *
     * @param bussId   商家编号
     * @param nowPage  当前页
     * @param pageSize @return
     * @return
     */
    @Override
    public List<Map<String, Object>> findAllGoodsList(Integer bussId, Integer nowPage, int pageSize) {
        return goodsDao.findAllGoodsList(bussId, nowPage, pageSize);
    }

    @Override
    public Map<String, Object> goodsPay(Integer goodsId, Integer busId, BigDecimal money, Integer payType) {
        String kid = KidUtils.getKKid();
        Map map = new HashedMap();
        Goods goods = goodsDao.getEntityById(goodsId);
        Bussiness business = bussinessDao.getEntityById(busId);
        String title = business.getBussName() + "申请" + goods.getName() + "为特价商品付款：" + money + "元";
        //1支付宝、2微信
        if (payType == 1) {
            //支付宝
            String aplipay = AppPay.createPay(title, kid, title, money.doubleValue());//这里传的是支付订单编号
            map.put("pay", aplipay);
        } else if (payType == 2) {
            int price = money.multiply(BigDecimal.valueOf(100)).intValue();
            WeixinPay weixinPay = new com.weixin.pay.api.AppPay();
            PayInfo payInfo = new PayInfo();
            payInfo.setBody(title);
            payInfo.setTradeNo(kid);
            payInfo.setSubject(title);
            payInfo.setPrice(price);
            payInfo.loadWxConfig("wx48217cb07b14d413");
            weixinPay.setPayInfo(payInfo);
            map = weixinPay.createPay();
        }
        return map;
    }

    /**
     * 添加缴费记录，修改商品为特价商品
     *
     * @param goodsId
     * @param busId
     * @param payType
     * @param money
     * @param day
     * @param goodsDiscountPrice
     * @param discountNumber
     * @return
     */
    @Override
    public boolean addGoodsPayHistory(Integer goodsId, Integer busId, Integer payType, BigDecimal money, Integer day, BigDecimal goodsDiscountPrice, Integer discountNumber) {
        boolean flag = false;
        CompanyPanymentHistory companyPanymentHistory = new CompanyPanymentHistory();
        companyPanymentHistory.setCompanyId(busId);
        companyPanymentHistory.setPaymentMoney(money);
        companyPanymentHistory.setPaymentTime(day);
        companyPanymentHistory.setPaymentType(payHistory.每日特价.getCode());
        companyPanymentHistory.setCreatedTime(new Date());
        companyPanymentHistory.setRecommendId(0);
        companyPanymentHistory.setPayType(payType);
        companyPanymentHistory.setWaiterServiceId(0);
        companyPanymentHistory.setCarouselId(0);
        companyPanymentHistory.setGoodId(goodsId);
        flag = companyPanymentHistoryDao.save(companyPanymentHistory) > 0;
        if (flag) {
            Date expirationTime = DateUtil.addDate(new Date(), day);
            //修改商品为特价商品，并修改特价到期时间
            flag = goodsDao.updateIsSpecial(goodsId, expirationTime, goodsDiscountPrice, discountNumber);
        }
        return flag;
    }

    /**
     * @param nowPage
     * @param pageSize
     * @param goodsName
     * @param isSpecial
     * @param bussName
     * @param type
     * @return
     */
    @Override
    public Page findGoods(int nowPage, int pageSize, String goodsName, int isSpecial, String bussName, Integer type) {
        return goodsDao.findGoods(nowPage, pageSize, goodsName, isSpecial, bussName, type);
    }

    /**
     * @param id
     * @param isSpecial
     * @return
     */
    @Override
    public int noUpper(int id, Integer isSpecial) {
        return goodsDao.noUpper(id, isSpecial);
    }

    /**
     * @param nowPage
     * @param pageSize
     * @param goodsName
     * @param busName
     * @return
     */
    @Override
    public Page noUpperList(int nowPage, int pageSize, String goodsName, String busName) {
        return goodsDao.noUpperList(nowPage, pageSize, goodsName, busName);
    }

    /**
     * @param id
     * @return
     */
    @Override
    public int yesUpper(int id) {
        return goodsDao.yesUpper(id);
    }

    /**
     * @param id
     * @return
     */
    @Override
    public int deleteGoodsById(int id) {
        return goodsDao.deleteGoodsById(id);
    }

    /**
     * 查询每日特价的商品
     *
     * @param nowPage
     * @param pageSize
     * @param goodsName
     * @return
     */
    @Override
    public Page queryDayOffer(int nowPage, int pageSize, String goodsName) {
        return goodsDao.queryDayOffer(nowPage, pageSize, goodsName);
    }

    @Override
    public Map<String, Object> getShareGoodsById(Integer id) {
        Map<String, Object> map = new HashMap<String, Object>();
        Goods goods = goodsDao.getGoodsById(id);
        if (goods != null) {
            map = goods.toMap();
        }
        List<Map<String, Object>> specValues = goodsSpecService.findGoodsSpecByGoodsId(id);
        //判断是否为空
        if (specValues.size() > 0) {
            map.put("spec", specValues);
        } else {
            map.put("spec", specValues);
        }
        return map;
    }

    /**
     * @param id
     * @param goodsName
     * @param nowPage
     * @param pageSize  @return
     */
    @Override
    public Page businessGoods(Integer id, String goodsName, int nowPage, int pageSize) {
        return goodsDao.businessGoods(id, goodsName, nowPage, pageSize);
    }

    @Override
    public Page getOrderListByGoodsId(int nowPage, int pageSize, int id, String cstart, Integer jyjlzffs) {
        return orderDetailsDao.getOrderListByGoodsId(nowPage, pageSize, id, cstart, jyjlzffs);
    }

    @Override
    public List<Map<String, Object>> findEquipmentList(int companyTypeId, int nowPage, int pageSize, int userId) {
        List<Map<String, Object>> list = goodsDao.findEquipmentList(companyTypeId, nowPage, pageSize, userId);
        if (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                List<Map<String, Object>> maps = goodsSpecService.findGoodsSpecByGoodsId(Integer.parseInt(list.get(i).get("id").toString()));
                list.get(i).put("spec", maps);
            }
            return list;
        }
        return new ArrayList<>();
    }

    @Override
    public Map<String, Object> findEquipmentInfo(int companyTypeId, double ulat, double ulng, int userId) throws ServiceException {
        Bussiness business = bussinessDao.getBussinessByTypeId(companyTypeId);
        Integer bussId = business.getId();
        Map<String, Object> map = bussinessDao.getBussinessDateial(business.getId());
        if (ulat == 0D && ulng == 0D) {
            throw new ServiceException("请确认是否开启定位，并前往开阔地带！");
        }
//        if (map == null) {
//            throw new ServiceException("商家已被刪除或禁用");
//        }
        //获取商家的经纬度
        double buslng = Double.parseDouble(map.get("lng").toString());
        double buslat = Double.parseDouble(map.get("lat").toString());
        //计算距离
        double distace = Spatial4jUtil.getDistance(ulng, ulat, buslng, buslat);

//        System.out.println(distace);
        //统计月售份额
        int orderCount = orderService.getCountByMouthAndBusssId(business.getId());
        //统计商家的商品数量
        int goodsNumber = goodsDao.getCompanyGoodsNumber(bussId);
        //是否收藏
        int isFavorites = favoritesDao.getCountByUserAndBusId(bussId, userId, 1);
        //遍历获取商家的优惠劵
        List<Map<String, Object>> couponList = couponDao.getCouponByBussId(bussId);
//        StringBuffer sb = new StringBuffer();
//        for (int i = 0; i < couponList.size(); i++) {
//            sb.append(couponList.get(i).get("name"));
//            if (i > 0) {
//                sb.append("," + couponList.get(i).get("name"));
//            }
//        }
        map.put("couponList", couponList);
        //遍历获取商家的优惠活动
        List<Map<String, Object>> promotionList = promotionDao.getPromotionByBussId(bussId);
        StringBuffer promotion = new StringBuffer();
        if (promotionList.size() > 0) {
            for (int i = 0; i < promotionList.size(); i++) {
                if (i > 0) {
                    promotion.append(";  " + promotionList.get(i).get("name"));
                } else {
                    promotion.append(promotionList.get(i).get("name"));
                }

            }
            map.put("promotionList", promotion.toString());
        } else {
            map.put("promotionList", "");
        }
        map.put("startNumber", 5);
        double dispatching = 0D;
        BigDecimal bigDecimal = new BigDecimal(distace);
        map.put("distace", bigDecimal.setScale(2, RoundingMode.HALF_EVEN));
        map.put("serviceLince", business.getServiceLince());
        map.put("bussLicnese", business.getBussLicnese());
        map.put("companyStatus", business.getState());
        map.put("otherLicenses", business.getOtherLicenses());
        map.put("otherLicensesTwo", business.getOtherLicensesTwo());
        map.put("orderCount", orderCount);
        map.put("goodsNumber", goodsNumber);
        map.put("isFavorites", isFavorites);
        map.put("dispatching", dispatching);
        map.put("RyToken", JSONObject.fromObject(business.getRyToken()).get("token"));
        map.put("RyId", JSONObject.fromObject(business.getRyToken()).get("userId"));
        return map;
    }

    @Override
    public Map<String, Object> discountDetail(Integer goodsId) throws ServiceException {
        Goods goods = goodsDao.getEntityById(goodsId);
        if (goods == null) {
            throw new ServiceException("商品信息错误，请确认是否存在！");
        }
        Map<String, Object> map = new HashMap<>(1);
        CompanyPanymentHistory companyPanymentHistory = companyPanymentHistoryDao.gethistoryByGoodsId(goodsId);
        map.put("created", companyPanymentHistory.getCreatedTime());
        map.put("expirationTime", goods.getExpirationTime());
        //实例化到期时间
        Calendar expirationCalendar = Calendar.getInstance();
        expirationCalendar.setTime(goods.getExpirationTime());
        //实例化当前时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        //计算剩余天数
        int longTime = expirationCalendar.getTime().compareTo(calendar.getTime());
        map.put("applyDay", companyPanymentHistory.getPaymentTime());
        map.put("Day", longTime);
        map.put("price", goods.getPrice());
        map.put("discountPrice", goods.getDiscountMoney());
        map.put("discountNumber", goods.getDiscountNumber());
        map.put("stock", goods.getStock());
        return map;
    }
}
